from PyQt5.QtWidgets import (
    QWidget, QVBoxLayout, QLabel, QLineEdit, QTextEdit,
    QPushButton, QScrollArea, QSizePolicy
)
from PyQt5.QtCore import Qt, QDateTime
from PyQt5.QtGui import QPalette, QColor
from data_manager import append_message, load_messages


class MessageView(QWidget):
    def __init__(self):
        super().__init__()
        layout = QVBoxLayout(self)

        # 姓名输入
        layout.addWidget(QLabel("姓名："))
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("请输入姓名（可留空）")
        layout.addWidget(self.name_input)

        # 留言输入
        layout.addWidget(QLabel("留言："))
        self.text_input = QTextEdit()
        self.text_input.setPlaceholderText("请输入要留言的内容……")
        layout.addWidget(self.text_input)

        # 提交按钮
        self.btn = QPushButton("提交留言")
        self.btn.clicked.connect(self._submit)
        layout.addWidget(self.btn)

        # 留言列表标题
        layout.addWidget(QLabel("留言列表："))

        # 滚动区域
        self.scroll = QScrollArea()
        self.scroll.setWidgetResizable(True)

        # 滚动区域内部容器 修复：设置背景色+尺寸策略
        self.container = QWidget()
        self.container.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # 强制设置背景色，确保 Scribble 生效
        pal = self.container.palette()
        pal.setColor(QPalette.Window, QColor("#222222"))
        self.container.setAutoFillBackground(True)
        self.container.setPalette(pal)

        # 布局
        self.container_layout = QVBoxLayout(self.container)
        self.container_layout.setSpacing(6)
        self.scroll.setWidget(self.container)

        layout.addWidget(self.scroll, 1)

        # 初次加载留言
        self._reload()

    def _submit(self):
        """提交留言"""
        name = self.name_input.text().strip() or "匿名"
        content = self.text_input.toPlainText().strip()
        if not content:
            return
        now_str = QDateTime.currentDateTime().toString("yyyy-MM-dd HH:mm:ss")
        append_message(name, content, now_str)
        self.text_input.clear()
        self._reload()

    def _reload(self):
        """加载留言列表"""
        # 清空旧内容
        while self.container_layout.count():
            item = self.container_layout.takeAt(0)
            w = item.widget()
            if w:
                w.deleteLater()

        # 加载数据
        msgs = load_messages()

        if not msgs:
            self.container_layout.addWidget(QLabel("暂无留言"))
        else:
            for m in msgs:
                lbl = QLabel(f"{m.get('time', '')} - {m.get('name', '')}: {m.get('content', '')}")
                lbl.setWordWrap(True)
                self.container_layout.addWidget(lbl)

        self.container_layout.addStretch(1)

        self.container.update()

        self.scroll.verticalScrollBar().setValue(
            self.scroll.verticalScrollBar().maximum()
        )
